<template>
  <div>
    <div class="button-container">
      <button class="button" @click="downloadFile('/downloadUser')">下载用户信息表</button>
      <button class="button" @click="downloadFile('/downloadAdvice')">下载意见信息表</button>
      <button class="button" @click="downloadFile('/downloadWeight')">下载分析数据表</button>
      <button class="button" @click="isResetting = !isResetting">重置密码</button>
    </div>
    <hr width="100%" color="#987cb9" style="border:1px dashed #987cb9" size="1">
    <div class="button-container">
      预存文字：
      <input type="file" accept=".xls,.xlsx" ref="fileRef" style="display: none" @change="pickFile">
      <button class="button" @click="uploadTheory">上传替换鸡汤文</button>
      <button class="button" @click="downloadFile('/downloadTheory')">下载鸡汤文</button>
      *支持 .xlsx文本
    </div>
    <hr width="100%" color="#987cb9" style="border:1px dashed #987cb9" size="1">
    <div>
      <div class="button-container">
        编辑文字新闻
        <textarea v-model="newsInfo.news" style="margin-left:20px;resize: none" name="" id="" cols="50"
                  rows="8"></textarea>
      </div>
      <div class="button-container">显示时间
        <input style="margin-left:52px;" v-model="newsInfo.showtime" type="text"
               oninput="this.value=this.value.replace(/[^0-9]/g,'')">小时(整数)
      </div>
      <button class="button" @click="releaseNews">发布</button>
      <!--新闻列表-->
      <table align="center" v-if="newsList.length!=0" border="1" class="borderless-table">
        <tr>
          <th>文字新闻显示</th>
          <th>发布时间</th>
          <th>结束时间</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in newsList">
          <td>{{ item.news }}</td>
          <td>{{ item.begintime }}</td>
          <td>{{ item.endtime }}</td>
          <td style="color: blue;text-decoration: underline;cursor:pointer;" @click="stopNews(item)">停用</td>
        </tr>
      </table>
    </div>
    <hr width="100%" color="#987cb9" style="border:1px dashed #987cb9" size="1">
    <div>
      <div class="button-container">
        首页弹出广告
        <button class="button" @click="uploadHomeAdsImg">添加图片</button>*尺寸宽 500px X 高 700px
        <input type="file" accept="image/*" ref="homeAdsRef" style="display: none" @change="pickImgFile">
        <img :src="homeAdsImgInfo.url" style="width: 14%;height: 14%"/>
      </div>
      <input type="hidden" v-model="homeAdsInfo.imgSrc">
      <div class="button-container">
        跳转链接
        <textarea v-model="homeAdsInfo.jumpUrl" style="margin-left:20px;resize: none" name="" id="" cols="100"
                  rows="4"></textarea>
      </div>
      <div class="button-container">
        <button class="button" @click="releaseHomeAds">发布</button>
      </div>
      <!--首页广告列表-->
      <table align="center" v-if="homeAdsList.length!=0" border="1" style="width: 50%" class="borderless-table">
        <tr>
          <th>首页弹出广告图</th>
          <th>发布时间</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in homeAdsList">
          <td style=""><img :src="item.imgSrc"/></td>
          <td style="">{{ item.releaseTime }}</td>
          <td style="color: blue;text-decoration: underline;cursor:pointer;" @click="stopHomeAds">停用</td>
        </tr>
      </table>
    </div>
    <hr width="100%" color="#987cb9" style="border:1px dashed #987cb9" size="1">
    <div>
      <div class="button-container">
        楼层广告
        <button class="button" @click="uploadFloorAdsImg">添加图片</button>*尺寸宽 370px X 高 150px
        <input type="file" accept="image/*" ref="floorAdsRef" style="display: none" @change="pickImgFiles">
        <img :src="floorAdsImgInfo.url" style="width: 14%;height: 14%"/>
      </div>
      <input type="hidden" v-model="floorAdsInfo.imgSrc">
      <div class="button-container">
        跳转链接
        <textarea v-model="floorAdsInfo.jumpUrl" style="margin-left:20px;resize: none" name="" id="" cols="100"
                  rows="4"></textarea>
      </div>
      <div class="button-container">
        <button class="button" @click="releaseFloorAds">发布</button>
      </div>
      <!--楼层广告列表-->
      <table align="center" v-if="floorAdsList.length!=0" border="1" style="width: 50%" class="borderless-table">
        <tr>
          <th>首页楼层广告图</th>
          <th>发布时间</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in floorAdsList">
          <td style=""><img :src="item.imgSrc"/></td>
          <td style="">{{ item.releaseTime }}</td>
          <td style="color: blue;text-decoration: underline;cursor:pointer;" @click="stopFloorAds(item)">停用</td>
        </tr>
      </table>
    </div>
    <hr width="100%" v-if="isResetting" color="#987cb9" style="border:1px dashed #987cb9" size="1">
    <div class="login-form" v-if="isResetting">
      <div v-if="isResetting" class="login-form__inner">
        <h2 class="login-title">重置密码</h2>
        <input v-model="oldPassword" placeholder="请输入旧密码" class="login-input"/>
        <input v-model="newPassword" type="password" placeholder="请输入新密码" class="login-input"/>
        <input v-model="confirmPassword" type="password" placeholder="请确认新密码" class="login-input"/>
        <div class="button-group">
          <button @click="resetPassword" class="login-btn">提交</button>
          <button @click="isResetting = false" class="login-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {downloadUrl, imgUrl} from "../config/index.js";
import md5 from "js-md5";
import http from "../request/http.js";

export default {
  name: "LayoutPage",
  data() {
    return {
      oldPassword: '',
      newPassword: '',
      confirmPassword: '',
      isResetting: false,
      newsInfo: {
        news: "",
        showtime: 0
      },
      newsList: [],
      homeAdsImgInfo:{
        width:0,
        height:0,
        url:''
      },
      homeAdsInfo:{
        imgSrc:"",
        jumpUrl:""
      },
      homeAdsList:[],
      floorAdsImgInfo:{
        width:0,
        height:0,
        url:""
      },
      floorAdsInfo:{
        imgSrc:"",
        jumpUrl: ""
      },
      floorAdsList:[]
    }
  },
  methods: {
    uploadTheory() {
      this.$refs.fileRef.value = null;
      this.$refs.fileRef.click();
    },
    async pickFile(event) {
      console.log(event)
      var file = event.target.files[0];
      var fd = new FormData();
      fd.append("file", file);
      const res = await http({
        url: '/api/uploadTheory',
        method: 'post',
        data: fd,
        headers: {'Content-Type': 'multipart/form-data'}
      })
      if (res.success) {
        window.alert('上传成功!');
        this.$refs.fileRef.value = null;
      }
      this.$refs.fileRef.value = null;
    },
    // 下载文件
    downloadFile(url) {
      window.location.href = downloadUrl + url + "?token=" + localStorage.getItem('token');
    },
    // 发布新闻
    async releaseNews() {
      console.log(this.newsInfo)
      if(this.newsInfo.news===""){
        window.alert("新闻内容不能为空!");
        return false;
      }
      const res = await http({
        url: '/api/setNews',
        data: {
          news: this.newsInfo.news,
          showtime: this.newsInfo.showtime
        },
        method: 'post',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      });
      if (res.success) {
        window.alert('发布成功');
        this.home
        this.getNewsList();
      }
    },
    async resetPassword() {
      if (this.newPassword !== this.confirmPassword) {
        alert('两次输入的密码不一致');
        return;
      }
      const md5old = md5(this.oldPassword);
      const md5Pwd = md5(this.newPassword);
      console.log(md5old);
      console.log(md5Pwd)
      const res = await http({
        url: '/api/resetPassword',
        method: 'post',
        data: {
          token: localStorage.getItem('token'),
          oldPassword: md5old,
          newPassword: md5Pwd,
        }
      });
      console.log(res)
      if (res.success === true) {
        alert('重置密码成功');
        // 重置密码成功，显示下载按钮并隐藏重置密码部分
        this.isResetting = false;
      } else {
        alert('重置密码失败');
      }
    },
    async getNewsList() {
      const data = await http({
        url: '/api/newsList',
        method: 'get'
      });
      this.newsList = data.data;
    },
    async getHomeAdsList(){
      const data = await http({
        url:'/api/homeAdsList',
        method:'get'
      });
      data.data.map(item => {
        return item.imgSrc = imgUrl+item.imgSrc
      })
      this.homeAdsList = data.data
    },
    async getFloorAdsList(){
      const data = await http({
        url:'/api/getFloorAdsList',
        method:'get'
      });
      data.data.map(item => {
        return item.imgSrc = imgUrl+item.imgSrc
      })
      this.floorAdsList = data.data
    },
    async stopNews(e){
      const data = await http({
        url:'/api/stopNews',
        data:{
          id:e.id
        },
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        method:'post'
      });
      if(data.success){
        window.alert('已停用')
        this.getNewsList();
      }
      console.log(data)
    },
    uploadHomeAdsImg() {
      this.$refs.homeAdsRef.value = null;
      this.homeAdsImgInfo.url = "";
      this.$refs.homeAdsRef.click();
    },
    async pickImgFile(event) {
      var file = event.target.files[0];
      let self = this;
      // 定义reader对象获取图片尺寸
      var reader = new FileReader();
      reader.onload = function (event) {
        var img = new Image();
        img.onload = function (){
          var width = this.width;
          var height = this.height;
          self.homeAdsImgInfo.width = width;
          self.homeAdsImgInfo.height = height;
        }
        img.src = event.target.result;
      };
      reader.readAsDataURL(file);
      var fd = new FormData();
      fd.append("file", file);
      console.log(file)
      const res = await http({
        url: '/api/uploadImg',
        method: 'post',
        data: fd,
        headers: {'Content-Type': 'multipart/form-data'}
      })
      console.log(res)
      if (res.success) {
        window.alert('上传成功!');
        this.homeAdsImgInfo.url = imgUrl+res.data
        this.homeAdsInfo.imgSrc = res.data;
        this.$refs.homeAdsRef.value = null;
      }
      this.$refs.homeAdsRef.value = null;
    },
    async releaseHomeAds(){
      if(this.homeAdsInfo.imgSrc === ""){
        window.alert("请填写首页广告信息");
        return false;
      }
      const data = await http({
        url:'/api/addHomeAds',
        data:this.homeAdsInfo,
        method:'post'
      });
      if(data.success){
        window.alert("发布成功");
        this.homeAdsImgInfo.url = "";
        this.getHomeAdsList();
      }
      console.log(data)
    },
    async stopHomeAds(){
      const data = await http({
        url:'/api/stopHomeAds',
        method:'post'
      });
      if(data.success){
        window.alert("已停用");
        this.getHomeAdsList();
      }
    },
    uploadFloorAdsImg() {
      this.$refs.floorAdsRef.value = null;
      this.floorAdsImgInfo.url = "";
      this.$refs.floorAdsRef.click();
    },
    async pickImgFiles(event) {
      var file = event.target.files[0];
      let self = this;
      // 定义reader对象获取图片尺寸
      var reader = new FileReader();
      reader.onload = function (event) {
        var img = new Image();
        img.onload = function (){
          var width = this.width;
          var height = this.height;
          self.floorAdsImgInfo.width = width;
          self.floorAdsImgInfo.height = height;
        }
        img.src = event.target.result;
      };
      reader.readAsDataURL(file);
      var fd = new FormData();
      fd.append("file", file);
      console.log(file)
      const res = await http({
        url: '/api/uploadImg',
        method: 'post',
        data: fd,
        headers: {'Content-Type': 'multipart/form-data'}
      })
      console.log(res)
      if (res.success) {
        window.alert('上传成功!');
        this.floorAdsImgInfo.url = imgUrl+res.data
        this.floorAdsInfo.imgSrc = res.data;
        this.$refs.floorAdsRef.value = null;
      }
      this.$refs.floorAdsRef.value = null;
    },
    async releaseFloorAds(){
      if(this.floorAdsInfo.imgSrc === ""){
        window.alert("请填写楼层广告信息");
        return false;
      }
      const data = await http({
        url:'/api/addFloorAds',
        data:this.floorAdsInfo,
        method:'post'
      });
      if(data.success){
        window.alert("发布成功");
        this.floorAdsImgInfo.url = "";
        this.floorAdsInfo.imgSrc = "";
        this.getFloorAdsList();
      }
      console.log(data)
    },
    async stopFloorAds(e){
      const data = await http({
        url:'/api/stopFloorAds',
        data:{
          id:e.id
        },
        method:'post'
      });
      if(data.success){
        window.alert("已停用");
        this.getFloorAdsList();
      }
    }
  },
  async mounted() {
    this.getNewsList();
    this.getHomeAdsList();
    this.getFloorAdsList();
  }
}
</script>

<style scoped>
.button-container {
  display: flex;
  justify-content: flex-start !important;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 20px;
}

.button {
  display: block;
  width: 200px;
  height: 40px;
  padding: 10px;
  margin: 10px;
  font-size: 16px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.2s ease-in-out;
}

.button:hover {
  background-color: #1976d2;
}

.button-group {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.button-group button {
  margin: 0 10px;
}

.login-form {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 40px;
  /*min-height: 100vh;*/
  /*background-color: #f2f2f2;*/
}

.login-form__inner {
  background-color: white;
  padding: 30px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  text-align: center;
  animation: fadeIn 0.5s ease-in-out;
}

.login-title {
  margin-top: 0;
  margin-bottom: 20px;
}

.login-input {
  display: block;
  width: 100%;
  height: 40px;
  padding: 10px;
  margin-bottom: 20px;
  font-size: 16px;
  border-radius: 5px;
  border: 1px solid #ccc;
}

.login-btn {
  display: block;
  width: 100%;
  height: 40px;
  padding: 10px;
  margin-top: 20px;
  font-size: 16px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.2s ease-in-out;
}

.login-btn:hover {
  background-color: #1976d2;
}

.button-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 20px;
}

.button {
  display: block;
  width: 200px;
  height: 40px;
  padding: 10px;
  margin: 10px;
  font-size: 16px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.2s ease-in-out;
}

.borderless-table {
  border-collapse: collapse;
  border: 1px solid #000;
  margin-left: 0;
}

.borderless-table td, .borderless-table th {
  border: 1px solid #000;
  padding: 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.borderless-table td img{
  object-fit: cover;
  width: 10%;
  height: 10%;
}
</style>
